package com.star.robot.controller;

import com.star.robot.dto.PageResultDto;
import com.star.robot.dto.ResultDto;
import com.star.robot.dto.TeamBackendQueryDto;
import com.star.robot.dto.TeamRespDto;
import com.star.robot.entity.*;
import com.star.robot.enums.AdminTypeEnum;
import com.star.robot.enums.ProjectLevelEnum;
import com.star.robot.repository.ProjectRepository;
import com.star.robot.repository.TeamMemberRepository;
import com.star.robot.repository.TeamRepository;
import com.star.robot.repository.TeamScoreRepository;
import com.star.robot.service.AdminService;
import com.star.robot.specialficaition.TeamSpecial;
import com.star.robot.util.DtAreaUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "/team/backend")
public class TeamBackendController {

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private DtAreaUtil dtAreaUtil;

    @Autowired
    private TeamScoreRepository teamScoreRepository;

    @Autowired
    private TeamSpecial teamSpecial;

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private TeamMemberRepository teamMemberRepository;

    @Autowired
    private AdminService adminService;

    /**
     *
     * @param requestDto
     * @return
     */
    @GetMapping(value = "/backend")
    @ApiOperation(value = "队伍查询",notes = "队伍查询")
    public PageResultDto getBackend(TeamBackendQueryDto requestDto , HttpServletRequest request){
        PageResultDto<Team> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());


            AdminTypeEnum adminTypeEnum = adminService.getCurrentAdminLevel(request);
            log.info("队员管理查询　：　参数[adminTypeEnum] :"+adminTypeEnum.getName());



            if(requestDto.getCityId() == null){
                Long cityId = adminService.getCurrentAdminCityId(request);
                log.info("队员管理查询　：　参数[cityId] :"+cityId);
                requestDto.setCityId(cityId);
            }
            Page<Team> pageable = teamSpecial.findByRequestDto(page , requestDto);

            List<TeamRespDto> teamRespDtos = new ArrayList<>();
            if(	!CollectionUtils.isEmpty(pageable.getContent()) ) {
            	for(Team team :pageable.getContent()) {
                    String areaName = null;
                    String cityName = null;
                    String area = "";
                    if (!StringUtils.isEmpty(team.getCompany().getProvinceId())) {
                    	area += dtAreaUtil.getAreaName(Long.valueOf(team.getCompany().getProvinceId()));
    				}
                    if (!StringUtils.isEmpty(team.getCompany().getCityId())) {
                    	if (area.length()>0) {
                    		area += "-";
    					}
                    	area += dtAreaUtil.getAreaName(Long.valueOf(team.getCompany().getCityId()));
    				}
                    if (!StringUtils.isEmpty(team.getCompany().getAreaId())) {
                    	if (area.length()>0) {
                    		area += "-";
    					}
                    	area += dtAreaUtil.getAreaName(Long.valueOf(team.getCompany().getAreaId()));
    				}


                    Double scoreSum = teamScoreRepository.selectScoreSum(team.getId());
                    TeamRespDto teamRespDto = TeamRespDto.builder()
                    		.teamId(team.getId())
                            .areaName(areaName)
                            .cityName(cityName)
                            .companyType(team.getCompany().getCompanyType().getName())
                            .companyName(team.getCompany().getName())
                            .teamName(team.getTeamName())
                            .teamType(team.getProjectClassEnum().getName())
                            .teamScoreSum(scoreSum)
                            .memberCount(team.getTeamMembers().size())
                            .leaderCount(team.getTeamLeaders().size())
                            .location(area)
                            .projectName(team.getProject().getName())
                            .build();
                    if("1".equals(adminTypeEnum.getCode()))
                        if(team.getTemplateId() != null){
                            Team team2 = teamRepository.findLongByTemplateId(team.getId());
                            if(team2 == null){
                                teamRespDto.setChoosed(false);
                            }else {
                                teamRespDto.setChoosed(true);
                            }
                        }
                    teamRespDtos.add(teamRespDto);
            	}
            }

            Page pagedTeamMembers = new PageImpl(teamRespDtos , page ,pageable.getTotalElements() );
            results.setCount(pagedTeamMembers.getTotalElements());
            results.setData(pagedTeamMembers.getContent());

            return results;
        }
        return PageResultDto.builder().data(null).build();

    }


    /**
     * 缴费确认（省级使用）
     * @param ids
     * @return
     */
    @GetMapping(value = "/teamJiaofei")
    @ApiOperation(value = "后台缴费", notes = "后台缴费")
    public ResultDto teamJiaofei(List<Long> ids) {

        for (Long id : ids) {
            Team team = teamRepository.findById(id).get();

            Long countMember = teamMemberRepository.countTeamMember(team.getId());

            Float money = countMember * 100.00F;//TODO 这个100 需要配置参数，这里取参数

            JiaoFei jiaoFei = JiaoFei.builder()
                    .createTime(new Date())
                    .value(money)
                    .team(team)
                    .build();

            team.setJiaoFei(jiaoFei);
        }
        return ResultDto.builder().build();
    }

    /**
     * 选拔报名（市级使用）
     * @param id
     * @return
     */
    @GetMapping(value = "/xuanba")
    @ApiOperation(value = "选拔", notes = "选拔")
    public ResultDto xuanba(long id) {

        Team team = teamRepository.findById(id).get();

        //拷贝队伍基础信息
        Team sjTeam = new Team();
        sjTeam.setCreateTime(new Date());
        sjTeam.setTemplateId(team.getId());
        sjTeam.setProjectClassEnum(team.getProjectClassEnum());
        sjTeam.setTeamName(team.getTeamName());
        sjTeam.setCompany(team.getCompany());

        sjTeam.setTeamScores(null);

        Project project = projectRepository.findById(team.getProject().getParentid()).get();
        sjTeam.setProject(project);

        teamRepository.save(sjTeam);

        //拷贝老师
        for (TeamLeader teamLeader : team.getTeamLeaders()) {
            TeamLeader teamLeader1=new TeamLeader();
            teamLeader1.setPhone(teamLeader.getPhone());
            teamLeader1.setName(teamLeader.getName());
            teamLeader1.setTeam(sjTeam);

        }

        //拷贝队员
        for (TeamMember teamMember : team.getTeamMembers()) {
            TeamMember teamMember1=new TeamMember();
            teamMember1.setSchool(teamMember.getSchool());
            teamMember1.setIdCard(teamMember.getIdCard());
            teamMember1.setName(teamMember.getName());
            teamMember1.setSize(teamMember.getSize());
            teamMember1.setSex(teamMember.getSex());
            teamMember1.setTeam(sjTeam);
        }


        return ResultDto.builder().build();
    }

    /**
     * 选拔
     * @param id
     * @return
     */
    @GetMapping(value = "/choose")
    @ApiOperation(value = "选拔", notes = "选拔")
    public ResultDto choose(long id) {
        Team team = teamRepository.findById(id).get();
        team.setId(null);
        team.setTemplateId(id);
        team.setTeamScores(null);
        teamRepository.save(team);
        return ResultDto.builder().build();
    }
}
